package pl.edu.agh.persdoc.model;

import org.ektorp.CouchDbConnector;
import org.ektorp.ViewQuery;
import org.ektorp.ViewResult;
import org.ektorp.support.CouchDbRepositorySupport;
import org.ektorp.support.View;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class ScheduleRepository extends CouchDbRepositorySupport<Schedule> {

	@Autowired
	public ScheduleRepository(@Qualifier("blogPostDatabase") CouchDbConnector db) {
		super(Schedule.class, db);
		initStandardDesignDocument();
	}

	@View(name = "getLatestSchedule", map = "function(doc) { if(doc.schedule)emit(doc.creationDate, doc);}")
	public String getLatestSchedule() {

		ViewQuery q = createQuery("getLatestSchedule");
		ViewResult queryResult = db.queryView(q);
		if (queryResult != null && queryResult.getRows() != null
				&& queryResult.getRows().size() > 0) {
			
			for(int i=0;i<queryResult.getRows().size();i++){
				
				System.out.println("\n\nschedule:"+queryResult.getRows().get(i).getKey());
				
			}
			int lastRowIndex=queryResult.getRows().size()-1;
			String record = queryResult.getRows().get(lastRowIndex).getValue();
			String schedule = ViewResultParser.getScheduleFromRecord(record);
			System.out.println("latest schedule:" + schedule);
			return schedule;
		} else {
			System.out.println("no schedules found!");
			return null;
		}
	}

}